package raptor;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public abstract class SendRecieve {
    public static final Integer PORT = 8080;
    public static final Integer LENGTH = 1024;

    public void send(byte[] buf, InetAddress address, int port) {
        try {
            DatagramSocket socket = new DatagramSocket();
            DatagramPacket packet = new DatagramPacket(buf, buf.length, address, port);;
            socket.send(packet);
            socket.close();
        } catch(IOException io){}
    }
    
    public void listen(boolean server) {
        int i = 0;
        if(server) i++;

        byte[] buffer = new byte[LENGTH];
        int port = PORT + i;
        try {
            DatagramSocket socket = new DatagramSocket(port);
            System.out.println(socket.getInetAddress() + ":" + socket.getPort());

            while(true) {
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

                try {
                    socket.receive(packet);
                } catch(IOException ioe) {
                    System.out.println(ioe);
                }

                InetAddress client = packet.getAddress();
                int clientPort = packet.getPort();

                if(buffer.length != 0) output(buffer, client);
                //System.out.println(buffer.length);
                buffer = new byte[1024];
                //System.out.println(buffer.length);
            }
        } catch(SocketException se) {
            System.out.println("We've got and socket error, mentlegen." + se.getMessage());
        }
    }

    public abstract void output(byte[] buf, InetAddress client);
}
